/*
 * @Author: zi.yang
 * @Date: 2020-06-17 23:26:26
 * @LastEditTime: 2021-10-04 21:57:55
 * @LastEditors: zi.yang
 * @Description: app index
 * @FilePath: \project-management\app.js
 */

const express = require('express');
const app = express();
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const JwtUtil = require('./utils/jwt');

//设置跨域请求
app.all('*', function (req, res, next) {
  //指定允许其他域名访问
  res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8080');
  //允许的请求头字段
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type, Content-Length, Auth, Authorization, Accept, X-Requested-With'
  );
  //允许的请求类型
  res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
  //请求数据类型
  res.header('Content-Type', 'application/json;charset=utf-8');
  //是否允许后续请求携带认证信息（cookies）,该值只能是true,否则不返回
  res.header('Access-Control-Allow-Credentials', true);
  //预检结果缓存时间,缓存
  res.header('Access-Control-Max-Age', 1800);
  //修改 X-Powered-By 指定版本
  res.header('X-Powered-By', 'NodeJS');
  next();
});
const TOKEN_KEY = 'ZI.YANG-PM-USER-TOKEN';

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//设置public文件夹为存放静态文件的目录。
app.use(express.static(path.join(__dirname, 'public')));

// 请求拦截
app.use(function (req, res, next) {
  // 不对 login 进行token校验
  const path = ['/api/v1/users/login','/api/v1/users/refreshToken']
  if (path.includes(req.url.split('?')[0])) return next();

  const token = req.cookies[TOKEN_KEY]
  // 判断请求是否携带token
  if (!token) {
    res.status(401).json({ status: 401, msg: '用户请求未携带 token!' });
    return;
  }
  // 校验 token
  const jwt = new JwtUtil(token);
  let result = jwt.verifyToken();

  // 如果通过就next，否则就返回登陆信息不正确
  if (result !== 'err') return next();
  res.status(403).json({ status: 403, msg: '登录已过期,请重新登录!' });
});


// app.use(function(req,res,next){
//   console.log(req)
//   next()
// })

// api 接口路由
app.use('/api/v1', require('./controllers'));

// catch 404 and forward to error handler
app.use(function (req, res) {
  res.status(404).json({ status:404,msg:'System:请求路径不存在!'});
});

// no stack traces leaked to user
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).json({ status:500,msg:'System:系统运行时异常!'});
});

module.exports = app;
